// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bii_vg

//@version=5
indicator(title="Dema Supertrend | viResearch", overlay=true, timeframe="", timeframe_gaps=true)

import TradingView/ta/7              as ta

// vii`dema supertrend
subject 	   = input.int  (2,"Supertrend Len", minval = 2 , group="Dema Supertrend | viResearch")
mul            = input.float(3.35, "Supertrend Multiple", step=0.05,group="Dema Supertrend | viResearch")
demalen        = input.int  (9, "Dema len", group="Smoothing Dema Supertrend | viResearch")
src            = input.source(hlc3, "Dema source", group="Smoothing Dema Supertrend | viResearch")
dema           = ta.dema(src, demalen)

Dema_Supertrend(mul, atrPeriod) =>
    src = dema
    atr = ta.atr(atrPeriod)
    u = src + mul * atr
    l = src - mul * atr
    pl = nz(l[1])
    pu = nz(u[1])

    l := l > pl or close[1] < pl ? l : pl
    u := u < pu or close[1] > pu ? u : pu
    int d = na
    float st = na
    pt = st[1]
    if na(atr[1])
        d := 1
    else if pt == pu
        d := close > u ? -1 : 1
    else
        d := close < l ? 1 : -1
    st := d == -1 ? l : u
    [st, d]

[x, d] = Dema_Supertrend(mul, subject)

stl = ta.crossunder(d, 0)
sts = ta.crossover(d, 0)


L = stl
S = sts

var vii = 0

if L and not S 
	vii := 1

if S 
	vii := -1

src_plot = plot(src,"dema src", color = color.rgb(0, 255, 187, 100))
dema_plot = plot(dema,"dema", color = color.rgb(0, 255, 187, 100))
fill(src_plot, dema_plot, color = vii ==  1  ?  color.rgb(0, 255, 187) : vii == -1  ?  color.rgb(255, 0, 157) : na)
upTrend =    plot(d < 0 ? x : na, "Up Trend", color =  color.rgb(0, 255, 187), style = plot.style_linebr)
downTrend =  plot(d < 0 ? na : x, "Down Trend", color = color.rgb(255, 0, 157),   style = plot.style_linebr)
fill(dema_plot, upTrend,   color.rgb(0, 255, 187, 90), fillgaps = false)
fill(dema_plot, downTrend, color.rgb(255, 0, 157, 90), fillgaps = false)
alertcondition(L, title="Dema Supertrend Long", message="Dema Supertrend Long {{exchange}}:{{ticker}}")
alertcondition(S, title="Dema Supertrend Short", message="Dema Supertrend Short {{exchange}}:{{ticker}}")